package com.hluck.criminalintent

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.hluck.criminalintent.model.Crime
import java.text.SimpleDateFormat

/**
 *
 * @Author： LJH
 * @Time： 2023/11/20
 * @description：
 */

private const val VIEW_TYPE_NORMAL = 1
private const val VIEW_TYPE_POLICE = 2

class CrimeAdapter(var crimes:List<Crime>)
    :RecyclerView.Adapter<CrimeAdapter.CrimeHolder>() {

    inner class CrimeHolder(view: View):RecyclerView.ViewHolder(view),View.OnClickListener{

        private lateinit var crime:Crime

        init {
            itemView.setOnClickListener(this)

        }

        val titleTextView: TextView = view.findViewById(R.id.tv_crime_title)
        val dateTextView: TextView = view.findViewById(R.id.tv_crime_date)
        var callView: ImageView? = null


        fun bind(crime:Crime){
            this.crime = crime
            val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
            val crimeTime = format.format(crime.date)
            titleTextView.text = this.crime.title
            dateTextView.text = crimeTime
            if (crime.requiresPolice){
                callView = itemView.findViewById(R.id.iv_call)
                callView?.setOnClickListener {
                    Toast.makeText(itemView.context,"call policeman!",Toast.LENGTH_SHORT).show()
                }
            }
        }

        override fun onClick(p0: View?) {
            Toast.makeText(itemView.context,"${crime.title} pressed!",Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 负责创建要显示的视图，将其封装到一个ViewHolder里并返回结果
     * @param parent ViewGroup
     * @param viewType Int
     * @return CrimeHolder
     */
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CrimeHolder {
        val view = if (viewType == VIEW_TYPE_NORMAL){
            LayoutInflater.from(parent.context).inflate(R.layout.list_item_crime,parent,false)
        } else LayoutInflater.from(parent.context).inflate(R.layout.list_item_police,parent,false)
        return CrimeHolder(view)
    }

    /**
     * 绑定数据
     * @param holder CrimeHolder
     * @param position Int
     */
    override fun onBindViewHolder(holder: CrimeHolder, position: Int) {
        val crime = crimes[position]
//        holder.apply {
//            titleTextView.text = crime.title
//            dateTextView.text = crime.date.toString()
//        }
        holder.bind(crime)
    }

    override fun getItemCount(): Int = crimes.size

    override fun getItemViewType(position: Int): Int {
        return if (crimes[position].requiresPolice) VIEW_TYPE_POLICE else VIEW_TYPE_NORMAL
    }
}